<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Website;
use App\MonitoringRecord;
use App\Mail\WebsiteError;
use Illuminate\Support\Facades\Mail;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $user = auth()->user();
        $websites = $user->websites()->get();
        $websites_id = $user->websites()->pluck('id');
        $records = MonitoringRecord::whereIn('website_id', $websites_id)->latest()->take(count($websites))->get();
        foreach ($websites as $key => &$value) {
            foreach ($records as $k => $v) {
                if ($value['id'] == $v['website_id']) {
                    $value['record'] = $v;
                    continue 2;
                }
            }
        }
        return view('home', compact('websites'));
    }

    public function createMonitor(Request $request)
    {
        $url = $request->url;
        if ($url) {
            $user = auth()->user();
            $user->websites()->create(['url'=>$url]);
            return redirect('home')->with('status', 'Create Success');
        } else {
            abort(404);
        }
    }

    public function deleteMonitor($id)
    {
        $user = auth()->user();
        $website = $user->websites()->findOrFail($id);
        $website->delete();
        return back()->with('status', 'Delete Success');
    }

    public function records($id)
    {
        $user = auth()->user();
        $website = $user->websites()->findOrFail($id);
        $records = $website->monitoringRecords()->latest()->get();
        return view('records', compact('records'));
    }
}
